package com.hx.thread.condition;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;

/**
 * @author Minghua Chen
 * @date 2020-09-06 10:25
 */
public class MyBlockingQueueForWaitNotify {

    private static final Logger logger = LoggerFactory.getLogger(MyBlockingQueueForWaitNotify.class);

    private int maxSize;
    private LinkedList<Object> storage;

    public MyBlockingQueueForWaitNotify(int maxSize) {
        this.maxSize = maxSize;
        storage = new LinkedList<>();
    }

    public synchronized void put() throws InterruptedException {
        while (storage.size() == maxSize) {
            // 阻塞  但是会释放锁
            this.wait();
        }
        storage.add(new Object());
        // 通知消费线程可以进行消费
        this.notifyAll();
    }

    public synchronized void take() throws InterruptedException {
        while (storage.size() == 0) {
            // 进入等待 会释放锁
            this.wait();
        }
        logger.info("" + storage.remove());
        // 移除元素后会通知生产线程进行生产
        this.notifyAll();
    }
}
